import fetch from 'dva/fetch';
import { notification } from 'antd';
import router from 'umi/router';

function parseJSON(response) {
	return response.json();
}

function checkStatus(response) {
	if (response.status >= 200 && response.status < 300) {
		return response;
	}
	if (response.status === 400) {
		router.push('/user/login');
		return;
	}
	const error_msg = `${response.status} ${response.statusText}`;
	notification.error({
		message: response.status,
		description: response.statusText,
	});
	const error = new Error(error_msg);
	error.response = response;
	throw error;
}

function checkCode(response) {
	if ((response.code >= 200 && response.code < 300) || response.code === 20000) {
		return response;
	}
	if (response.code === 401) {
		router.push('/user/login');
	}
	const error_msg = ` ${response.msg}`;
	notification.error({
		message: response.code,
		description: response.msg,
	});
	const error = new Error(error_msg);
	error.response = response;
	throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
	const defaultOptions = {
		//
	};
	const newOptions = { ...defaultOptions, ...options };
	const token =
		(localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).token) ||
		'';
	newOptions.headers = {
		'Access-Control-Allow-Origin': '*',
		'Access-Control-Allow-Credentials': true,
		'Cache-Control': 'no-cache',
		token,
		// "Access-Control-Allow-Methods":"OPTIONS, GET, POST,DELETE",
		// "Access-Control-Allow-Headers":"x-requested-with, accept, origin, content-type"
	};
	if (
		newOptions.method === 'POST' ||
		newOptions.method === 'PUT' ||
		newOptions.method === 'DELETE'
	) {
		if (!(newOptions.body instanceof FormData)) {
			newOptions.headers = {
				Accept: 'application/json',
				'Content-Type': 'application/json; charset=utf-8',
				...newOptions.headers,
			};
			newOptions.body = JSON.stringify(newOptions.body);
		} else {
			// newOptions.body is FormData
			newOptions.headers = {
				Accept: 'application/json',
				...newOptions.headers,
			};
		}
	}
	return fetch(url, newOptions)
		.then(checkStatus)
		.then(parseJSON)
		.then(checkCode)
		.then(data => data.data || data)
		.catch(err => {
			throw err;
		});
}
